<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
Corey Quon<br />
803786588<br />
CS 143 <br />
Type an expression in the following box:
<p>
<form method="POST" action="calculator.php">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>
<ul>
<li>Calculator supports +, -, *, and / operators and the evaluation of the input follows standard operator precedence.
<li>Calculator supports integers (eg. 1234) and real (eg. 123.45) numbers.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>
Evaluated Expression: <br />
</body>
</html>



<?php


$expression = $_POST["expr"];
$num_operands = 1;

// no characters besides numbers or [.+-*/]
$valid = true;

//If no input, don't evaluate
if($expression == NULL)
{
	$valid = false;
}

//If there are any characters besides 0-9 or .+-*/ then it will say it is an invalid expression since our calculator only supports those input
if(preg_match("/[^0-9\.\+\-\*\/\s]+/",$expression) > 0)
{
	$valid = false;
	echo "invalid expression";
}

//This takes care of dividing by 0 cases
else if(preg_match("/\/\s*0/",$expression) > 0)
{
	$valid = false;
	echo "invalid expression: dividing by 0";
}

//This will make sure there are not 2 operators in a row unless a - because that is used for negative numbers and . for a leading decimal number
else if(preg_match("/[\.\+\-\*\/]\s*[\+\*\/]+/",$expression) > 0)
{
	$valid = false;
	echo "invalid expression";
}

//This will make sure that decimal points . are separated by more than just numbers, or in other words they require an operand between them
else if(preg_match("/\.[0-9\s]*\./",$expression))
{
	$valid = false;
	echo "invalid expression";
}

//This will make sure the expression doesn't start without an operand (number) except - for negative numbers
else if(preg_match("/^{[0-9]|\-[0-9]+}/",$expression))
{
	$valid = false;
	echo "invalid expression";
}

//This will make sure the expression doesn't end with a non operand (number)
else if(preg_match("/[\.\+\-\*\/]$/",$expression))
{
	$valid = false;
	echo "invalid expression";
}

echo "\n";

$expression = preg_replace("/\-{2}/","- -",$expression);	//replaces -- with - -, it allows the eval to work properly

if($valid == true)
{
	//Want to evaluate the expression and print it out
	eval("\$ans = $expression;");
	echo $expression;
	echo " = ";
	echo $ans;
}




?>